package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV2;
import com.atguigu.gmall.realtime.bean.OrderDetail;
import com.atguigu.gmall.realtime.bean.OrderInfo;
import com.atguigu.gmall.realtime.bean.OrderWide;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.DimAsyncFunction;
import com.atguigu.gmall.realtime.util.DimUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.atguigu.gmall.realtime.common.Constant.TOPIC_DWD_ORDER_DETAIL;
import static com.atguigu.gmall.realtime.common.Constant.TOPIC_DWD_ORDER_INFO;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/27 14:50
 */

public class DwmOrderWide_Cache_Async extends BaseAppV2 {
    public static void main(String[] args) {
        new DwmOrderWide_Cache_Async().init(3003, 1, "DwmOrderWide_Cache_Async", "DwmOrderWide_Cache_Async",
                                            TOPIC_DWD_ORDER_INFO, TOPIC_DWD_ORDER_DETAIL);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       Map<String, DataStreamSource<String>> streamMap) {
        
        // 1. 实时表的join: 流的join
        DataStream<OrderWide> orderWideWithoutDimStream = factJoin(streamMap);
        // 2. 维度表的join: 通过jdbc的去查询
        SingleOutputStreamOperator<OrderWide> orderWideWithDimStream = dimJoin(orderWideWithoutDimStream);
        // 3. 订单宽表数据写入到dwm层(kafka)
        writeToKafka(orderWideWithDimStream);
        
    }
    
    private void writeToKafka(SingleOutputStreamOperator<OrderWide> orderWideWithDimStream) {
        orderWideWithDimStream
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_ORDER_WIDE));
    }
    
    private SingleOutputStreamOperator<OrderWide> dimJoin(DataStream<OrderWide> orderWideWithoutDimStream) {
        return AsyncDataStream.unorderedWait(
            orderWideWithoutDimStream,
            new DimAsyncFunction<OrderWide>() {
                @Override
                protected void addDim(Connection conn,
                                      Jedis redis,
                                      OrderWide orderWide,
                                      ResultFuture<OrderWide> resultFuture) {
                    System.out.println("异步....");
                    // 1. 补充用户数据
                    JSONObject userInfo = DimUtil.getDim(conn, redis, "dim_user_info", orderWide.getUser_id());
                    orderWide.setUser_gender(userInfo.getString("GENDER"));
                    orderWide.calcUserAge(userInfo.getString("BIRTHDAY"));
                    // 2. 补充省份数据
                    JSONObject provinceInfo = DimUtil.getDim(conn, redis, "dim_base_province", orderWide.getProvince_id());
                    orderWide.setProvince_3166_2_code(provinceInfo.getString("ISO_3166_2"));
                    orderWide.setProvince_area_code(provinceInfo.getString("AREA_CODE"));
                    orderWide.setProvince_iso_code(provinceInfo.getString("ISO_CODE"));
                    orderWide.setProvince_name(provinceInfo.getString("NAME"));
                    // 3. 补充sku
                    JSONObject skuInfo = DimUtil.getDim(conn, redis, "dim_sku_info", orderWide.getSku_id());
                    orderWide.setSku_name(skuInfo.getString("SKU_NAME"));
                    orderWide.setOrder_price(skuInfo.getBigDecimal("PRICE"));
    
                    orderWide.setSpu_id(skuInfo.getLong("SPU_ID"));
                    orderWide.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                    orderWide.setTm_id(skuInfo.getLong("TM_ID"));
                    // 4. 补充spu
                    JSONObject spuInfo = DimUtil.getDim(conn, redis, "dim_spu_info", orderWide.getSpu_id());
                    orderWide.setSpu_name(spuInfo.getString("SPU_NAME"));
    
                    // 5. 补充 tm
                    JSONObject tmInfo = DimUtil.getDim(conn, redis, "dim_base_trademark", orderWide.getTm_id());
                    orderWide.setTm_name(tmInfo.getString("TM_NAME"));
                    // 5. 补充 c3
                    JSONObject c3Info = DimUtil.getDim(conn, redis, "dim_base_category3", orderWide.getCategory3_id());
                    orderWide.setCategory3_name(c3Info.getString("NAME"));
    
    
                    // 把补齐的结果交给 resultFuture
                    resultFuture.complete(Collections.singletonList(orderWide));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private DataStream<OrderWide> factJoin(Map<String, DataStreamSource<String>> streamMap) {
        KeyedStream<OrderInfo, Long> orderInfoStream = streamMap
            .get(TOPIC_DWD_ORDER_INFO)
            .map(s -> JSON.parseObject(s, OrderInfo.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderInfo>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((info, ts) -> info.getCreate_ts())
            )
            .keyBy(OrderInfo::getId);
        
        KeyedStream<OrderDetail, Long> orderDetailStream = streamMap
            .get(TOPIC_DWD_ORDER_DETAIL)
            .map(s -> JSON.parseObject(s, OrderDetail.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderDetail>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((detail, ts) -> detail.getCreate_ts())
            )
            .keyBy(OrderDetail::getOrder_id);
        
        return orderInfoStream
            .intervalJoin(orderDetailStream)
            .between(Time.seconds(-5), Time.seconds(5))
            .process(new ProcessJoinFunction<OrderInfo, OrderDetail, OrderWide>() {
                @Override
                public void processElement(OrderInfo left,
                                           OrderDetail right,
                                           Context ctx,
                                           Collector<OrderWide> out) throws Exception {
                    OrderWide orderWide = new OrderWide(left, right);
                    out.collect(orderWide);
                    
                }
            });
        
    }
}
